package cn.lovemmd.model.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lovemmd.model.admin.common.PageResult;
import cn.lovemmd.model.admin.entity.User;
import cn.lovemmd.model.admin.mapper.UserMapper;
import cn.lovemmd.model.admin.service.UserService;
import cn.lovemmd.model.admin.vo.UserVO;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 * 
 * @author TLS
 * @since 2024-01-01
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public PageResult<UserVO> getUserPage(Long current, Long size, String search, Integer status) {
        // 创建分页对象
        Page<User> page = new Page<>(current, size);
        
        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        // 搜索条件
        if (StringUtils.hasText(search)) {
            queryWrapper.like(User::getUName, search)
                    .or()
                    .like(User::getUQq, search)
                    .or()
                    .like(User::getUCode, search);
        }
        
        // 状态筛选
        if (status != null) {
            queryWrapper.eq(User::getUStatus, status);
        }
        
        // 按创建时间倒序
        queryWrapper.orderByDesc(User::getCreateTime);
        
        // 执行分页查询
        IPage<User> userPage = this.page(page, queryWrapper);
        
        // 转换为VO
        List<UserVO> userVOList = userPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 返回分页结果
        return new PageResult<>(userVOList, userPage.getTotal(), userPage.getCurrent(), userPage.getSize());
    }

    @Override
    public UserVO getUserById(Long id) {
        User user = this.getById(id);
        return user != null ? convertToVO(user) : null;
    }

    @Override
    public boolean updateUserPassword(Long userId, String newPassword) {
        User user = new User();
        user.setUId(userId);
        user.setUPassword(newPassword);
        return this.updateById(user);
    }

    @Override
    public boolean banUser(Long userId) {
        User user = new User();
        user.setUId(userId);
        user.setUStatus(1); // 1表示封禁
        return this.updateById(user);
    }

    @Override
    public boolean unbanUser(Long userId) {
        User user = new User();
        user.setUId(userId);
        user.setUStatus(0); // 0表示正常
        return this.updateById(user);
    }

    @Override
    public boolean deleteUser(Long userId) {
        return this.removeById(userId);
    }

    @Override
    public boolean deleteBatchUsers(List<Long> userIds) {
        return this.removeByIds(userIds);
    }

    @Override
    public Object getUserStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总用户数
        long totalCount = this.count();
        stats.put("total", totalCount);
        
        // 正常用户数
        long normalCount = this.count(new LambdaQueryWrapper<User>()
                .eq(User::getUStatus, 0));
        stats.put("normal", normalCount);
        
        // 封禁用户数
        long bannedCount = this.count(new LambdaQueryWrapper<User>()
                .eq(User::getUStatus, 1));
        stats.put("banned", bannedCount);
        
        return stats;
    }

    @Override
    public User getUserByUsername(String username) {
        return this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUName, username));
    }

    /**
     * 将User实体转换为UserVO
     */
    private UserVO convertToVO(User user) {
        UserVO vo = new UserVO();
        // 手动映射字段
        vo.setUId(user.getUId());
        vo.setUName(user.getUName());
        vo.setUCode(user.getUCode());
        vo.setUQq(user.getUQq());
        vo.setUStatus(user.getUStatus());
        vo.setCreateTime(user.getCreateTime());
        vo.setUpdateTime(user.getUpdateTime());
        return vo;
    }
}
